package com.example.memorycardgame.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.memorycardgame.R;
import com.example.memorycardgame.adapter.CardAdapter;
import com.example.memorycardgame.model.Card;
import com.example.memorycardgame.utils.DataStorageUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CardGame3Fragment extends Fragment implements CardAdapter.OnCardClickListener {
    private RecyclerView rvCards;
    private TextView tvScore;
    private Button btnRestart;
    private List<Card> cardList;
    private CardAdapter adapter;
    private int currentScore;
    private List<Card> chosenCards = new ArrayList<>();
    private boolean isProcessing;
    private Handler handler = new Handler();
    private ProfileFragment profileFragment;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_card_game_3, container, false);
        initViews(view);
        initGame();
        bindEvents();
        profileFragment = (ProfileFragment) getParentFragmentManager().findFragmentByTag("profile");
        return view;
    }

    private void initViews(View view) {
        rvCards = view.findViewById(R.id.rv_cards);
        tvScore = view.findViewById(R.id.tv_score);
        btnRestart = view.findViewById(R.id.btn_restart);
        rvCards.setLayoutManager(new GridLayoutManager(requireContext(), 4));
    }

    // 初始化3张牌游戏（24张牌，8种图案各3张）
    private void initGame() {
        currentScore = 0;
        isProcessing = false;
        chosenCards.clear();
        cardList = new ArrayList<>();

        List<Integer> resIds = new ArrayList<>();
        for (int i = 1; i <= 8; i++) {
            for (int j = 0; j < 3; j++) {
                resIds.add(getResources().getIdentifier("ic_card" + i, "drawable", requireContext().getPackageName()));
            }
        }
        Collections.shuffle(resIds);

        for (int i = 0; i < 24; i++) {
            cardList.add(new Card(resIds.get(i), i));
        }

        adapter = new CardAdapter(cardList, this);
        rvCards.setAdapter(adapter);
        updateScore();
    }

    private void bindEvents() {
        btnRestart.setOnClickListener(v -> initGame());
    }

    @Override
    public void onCardClick(int position) {
        Card card = cardList.get(position);
        if (isProcessing || card.isMatched() || card.isFlipped()) return;

        card.flip();
        adapter.notifyItemChanged(position);
        chosenCards.add(card);

        if (chosenCards.size() == 3) {
            isProcessing = true;
            // 检查3张牌是否匹配
            boolean isMatch = true;
            int resId = chosenCards.get(0).getImageResId();
            for (Card c : chosenCards) {
                if (c.getImageResId() != resId) {
                    isMatch = false;
                    break;
                }
            }

            if (isMatch) {
                // 匹配成功
                currentScore += 15;
                for (Card c : chosenCards) {
                    c.setMatched(true);
                }
            } else {
                // 匹配失败
                currentScore = Math.max(0, currentScore - 5);
                handler.postDelayed(() -> {
                    for (Card c : chosenCards) {
                        c.flip();
                        adapter.notifyItemChanged(c.getPosition());
                    }
                }, 1000);
            }
            chosenCards.clear();
            isProcessing = false;
            updateScore();
            checkGameOver();
        }
    }

    private void updateScore() {
        tvScore.setText("当前得分：" + currentScore);
    }

    private void checkGameOver() {
        for (Card card : cardList) {
            if (!card.isMatched()) return;
        }
        if (profileFragment != null) {
            profileFragment.updateHighScore(false, currentScore);
        }
    }
}